<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useForm, useFormRules } from '@/hooks/common/form';
import { $t } from '@/locales';
import { fetchDeptInfoSave, fetchGetDeptTypeList } from '@/service/api';
import { useLoading } from '~/packages/hooks';
import DeptTreeSelect from './dept-tree-select.vue';

type Model = Api.System.Dept.DeptInfoFormModel;

defineOptions({ name: 'DeptFormDrawer' });

interface Props {
  parentId?: CommonType.IdType;
  operateType: UI.TableOperateType;
  rowData?: Api.System.Dept.DeptInfoRecord | null;
  maxOrderNum?: number;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const { formRef, validate, restoreValidation } = useForm();
const { createRequiredRule } = useFormRules();

function createDefaultModel(): Model {
  return {
    id: '',
    code: '',
    name: '',
    shortName: '',
    type: '',
    enabled: 1,
    orderNum: (props.maxOrderNum || 0) + 10,
    remark: '',
    parentId: props.parentId || 0
  };
}

const model = ref<Model>(createDefaultModel());

type RuleKey = Extract<Model, 'code' | 'name' | 'shortName' | 'type' | 'orderNum' | 'enabled'>;
const rules = ref<Record<RuleKey, App.Global.FormRule>>({
  code: createRequiredRule($t('form.required')),
  name: createRequiredRule($t('form.required')),
  shortName: createRequiredRule($t('form.required')),
  type: createRequiredRule($t('form.required')),
  orderNum: createRequiredRule($t('form.required')),
  enabled: createRequiredRule($t('form.enabled'))
});

const visible = defineModel<boolean>('visible', {
  default: false
});
const title = computed(() => {
  const titles: Record<UI.TableOperateType, string> = {
    add: '新增部门',
    edit: '编辑部门'
  };
  return titles[props.operateType];
});

function handleInitModel() {
  model.value = createDefaultModel();

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model.value, props.rowData);
    if (model.value.parentId === null || model.value.parentId === undefined) {
      model.value.parentId = 0;
    }
  }
}

function closeDrawer() {
  visible.value = false;
}

const { loading, startLoading, endLoading } = useLoading(false);

async function handleSubmit() {
  try {
    await validate();
    startLoading();
    // request
    const { error } = await fetchDeptInfoSave(model.value);
    // success
    if (error) return;
    window.$message?.success($t('common.updateSuccess'));
    closeDrawer();
    emit('submitted');
  } finally {
    endLoading();
  }
}

// 部门类型
const deptTypeList = ref<Api.System.Dept.DeptTypeRecord[]>();

// 获取部门类型
async function getDeptTypeList() {
  const { data, error } = await fetchGetDeptTypeList();
  if (error) return;
  deptTypeList.value = data;
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
    getDeptTypeList();
  }
});
</script>

<template>
  <ElDrawer v-model="visible" :title="title" :close-on-click-modal="false" direction="rtl" size="450">
    <ElForm ref="formRef" :model="model" :rules="rules" label-position="top">
      <ElFormItem label="上级部门" prop="parentId">
        <DeptTreeSelect v-model="model.parentId" :disabled-chilren-id="model.id" placeholder="上级部门" />
      </ElFormItem>
      <ElFormItem label="部门名称" prop="name">
        <ElInput v-model="model.name" placeholder="部门名称" maxlength="100" show-word-limit />
      </ElFormItem>
      <ElFormItem label="部门编码" prop="code">
        <ElInput v-model="model.code" placeholder="部门编码" maxlength="100" show-word-limit />
      </ElFormItem>
      <ElFormItem label="部门简称" prop="shortName">
        <ElInput v-model="model.shortName" placeholder="部门简称" maxlength="100" show-word-limit />
      </ElFormItem>
      <ElFormItem label="部门类型" prop="type">
        <ElSelect v-model="model.type" placeholder="部门类型">
          <ElOption v-for="item in deptTypeList" :key="item.id" :value="item.code" :label="item.name" />
        </ElSelect>
      </ElFormItem>
      <ElFormItem :label="$t('form.orderNum')" prop="orderNum">
        <ElInputNumber
          v-model="model.orderNum"
          :placeholder="$t('form.orderNum')"
          :step="10"
          controls-position="right"
          :precision="0"
          class="wfull"
        />
      </ElFormItem>
      <ElFormItem :label="$t('form.enabled')" prop="enabled">
        <ElRadioGroup v-model="model.enabled">
          <ElRadio :label="$t('form.enabledOptions.enabled')" :value="1" />
          <ElRadio :label="$t('form.enabledOptions.disabled')" :value="0" />
        </ElRadioGroup>
      </ElFormItem>
      <ElFormItem label="备注" prop="remark">
        <ElInput v-model="model.remark" type="textarea" placeholder="备注" maxlength="500" show-word-limit />
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElSpace v-loading="loading" :size="16">
        <ElButton @click="closeDrawer">{{ $t('common.cancel') }}</ElButton>
        <ElButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</ElButton>
      </ElSpace>
    </template>
  </ElDrawer>
</template>

<style scoped>
:deep(.el-input-number .el-input__inner) {
  text-align: left;
}
</style>
